package com.ikun.service.impl;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ikun.dao.MaintenanceOrdersDao;
import com.ikun.entity.MaintenanceOrders;
import com.ikun.entity.req.MaintenanceOrderDTO;
import com.ikun.service.MaintenanceOrdersService;
import com.ikun.util.Result;

@Service
public class MaintenanceOrdersServiceImpl implements MaintenanceOrdersService {

    @Autowired
    private MaintenanceOrdersDao maintenanceOrdersDao;

    @Override
    public List<MaintenanceOrders> findAssignedOrders() {
        return maintenanceOrdersDao.findAssignedOrders();
    }

    @Override
    public List<MaintenanceOrders> findCompleted() {
        return maintenanceOrdersDao.findCompleted();
    }

    @Override
    public String addMaintenanceOrders(MaintenanceOrders req) {
        // 构建统一返回值对象 <T> 泛型 T -> MaintenanceOrders
        // Result<MaintenanceOrders> rsp = new Result<>();

        // MaintenanceOrders maintenanceOrders = new MaintenanceOrders();

        // req 请求数据
        // maintenanceOrders 实体类对象 存放临时数据
        // req -> maintenanceOrders 讲请求装在到对象中

        // 调用dao层操作数据库 插入数据
        int result = maintenanceOrdersDao.addMaintenanceOrders(req);
        if (result == 0) {
            return "维修工单添加失败";
            // rsp.success("插入失败");
        } else {
            return "维修工单添加成功";
            // rsp.success("插入成功");
        }

    }

    @Override
    public Result markOrderAsCompleted(Map<String, Object> params) {
        // 检查参数是否完整
        String orderId = (String)params.get("order_id");
        String staffId = (String)params.get("staff_id");
        int rows = maintenanceOrdersDao.markOrderAsCompleted(orderId, staffId);
        if (rows > 0) {
            Map<String, Object> data = new HashMap<>();
            data.put("complete_time", LocalDateTime.now().toString());
            data.put("status", 1);
            data.put("quality_check", "待检查");
            return Result.success("工单状态更新成功", data);
        }
        return Result.fail("工单状态更新失败");
    }

    @Override
    public Result getPendingOrders(Integer staffId) {
        List<MaintenanceOrderDTO> orders = maintenanceOrdersDao.getPendingOrders(staffId);
        return Result.success(orders);
    }

    @Override
    public List<MaintenanceOrderDTO> findAllWorkOrdersByMangerId(Integer mangerId) {
        return maintenanceOrdersDao.findAllWorkOrdersByMangerId(mangerId);
    }

    @Override
    public int assignStaff(String orderId, Integer staffId) {
        return maintenanceOrdersDao.assignStaff(orderId, staffId);
    }

    @Override
    public List<MaintenanceOrderDTO> findAllWorkOrders() {
        return maintenanceOrdersDao.findAllWorkOrders();
    }
}
